package com.cxlin.cwanandroid.ui.search

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter4.QuickAdapterHelper
import com.chad.library.adapter4.loadState.LoadState
import com.chad.library.adapter4.loadState.trailing.TrailingLoadStateAdapter
import com.cxlin.base.BaseFragment
import com.cxlin.base.ext.binding
import com.cxlin.base.ext.startActivity
import com.cxlin.base.ext.toast
import com.cxlin.base.mvi.ext.collectFLow
import com.cxlin.cwanandroid.App
import com.cxlin.cwanandroid.R
import com.cxlin.cwanandroid.databinding.FragmentSearchRecommendBinding
import com.cxlin.cwanandroid.model.bean.Hot
import com.cxlin.cwanandroid.ui.browser.BrowserActivity
import com.cxlin.cwanandroid.ui.login.LoginActivity
import com.cxlin.cwanandroid.ui.login.viewmodel.LoginViewModel
import com.cxlin.cwanandroid.ui.search.adapter.SearchAdapter
import com.cxlin.cwanandroid.ui.search.viewmodel.SearchRecommendViewModel
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagAdapter
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 *
 * @Author: chenxunlin
 * @Date: 2024/5/11 14:30
 */
class SearchRecommendFragment : BaseFragment() {

    private val binding by binding<FragmentSearchRecommendBinding>()
    private val viewModel by viewModel<SearchRecommendViewModel>()
    private val mHotList = mutableListOf<Hot>()
    private val mWebSitesList = mutableListOf<Hot>()
    private var key = ""
    private val mEmptyView: View by lazy {
        val view = layoutInflater.inflate(
            R.layout.empty_view, binding.recyclerView.parent as ViewGroup, false
        )
        val emptyTv = view.findViewById<TextView>(R.id.emptyTv)
        emptyTv.text = getString(R.string.try_another_key)
        view
    }
    private val mAdapter by lazy {
        SearchAdapter()
    }
    private lateinit var helper: QuickAdapterHelper

    override fun getLayoutId() = R.layout.fragment_search_recommend

    override fun initView() {
        binding.searchView.setOnClickListener {
            requireActivity().startActivity<SearchActivity>()
        }
        initTagLayout()
        intRecyclerView()
    }

    private fun initTagLayout() {
        binding.hotTagLayout.run {
            adapter = object : TagAdapter<Hot>(mHotList) {

                override fun getCount() = mHotList.size

                override fun getView(parent: FlowLayout, position: Int, t: Hot): View {
                    val tv = LayoutInflater.from(parent.context).inflate(
                        R.layout.tag, parent, false
                    ) as TextView
                    tv.text = t.name
                    return tv
                }

            }

            setOnTagClickListener { view, position, parent ->
                key = mHotList[position].name
                binding.searchView.apply {
                    requireActivity().startActivity<SearchActivity>(Bundle().apply {
                        putString("key", key)
                    })
//                    setIconified(false)
//                    setQuery(key,true)
                }
                true
            }
        }

        binding.webTagLayout.run {
            adapter = object : TagAdapter<Hot>(mWebSitesList) {

                override fun getCount() = mWebSitesList.size

                override fun getView(parent: FlowLayout, position: Int, t: Hot): View {
                    val tv = LayoutInflater.from(parent.context).inflate(
                        R.layout.tag, parent, false
                    ) as TextView
                    tv.text = t.name
                    return tv
                }

            }

            setOnTagClickListener { view, position, parent ->
                requireActivity().startActivity<BrowserActivity>(data = Bundle().apply {
                    putString("url", mWebSitesList[position].link)
                })
                true
            }
        }
    }

    private fun intRecyclerView() {
        mAdapter.run {
            addOnItemChildClickListener(
                R.id.articleStar
            ) { adapter, view, position ->
                if (App.CURRENT_USER == null) {
                    requireActivity().startActivity<LoginActivity>()
                } else {
                    mAdapter.getItem(position)?.run {
                        collect = !collect
                        viewModel.sendIntent(
                            SearchRecommendViewModel.SearchUiIntent.CollectArticle(
                                id, collect
                            )
                        )
                    }
                    mAdapter.notifyItemChanged(position)
                }
            }
            addOnItemChildClickListener(R.id.root) { adapter, view, position ->
                requireActivity().startActivity<BrowserActivity>(Bundle().apply {
                    putString("url", mAdapter.getItem(position)!!.link)
                })
            }
            stateView = mEmptyView
        }
        helper = QuickAdapterHelper.Builder(mAdapter).setTrailingLoadStateAdapter(object : TrailingLoadStateAdapter.OnTrailingListener {
                override fun onFailRetry() {
                    viewModel.sendIntent(SearchRecommendViewModel.SearchUiIntent.SearchHot(key, false))
                }

                override fun onLoad() {
                    viewModel.sendIntent(SearchRecommendViewModel.SearchUiIntent.SearchHot(key, false))
                }

            }).build()
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(requireActivity())
            adapter = helper.adapter

        }
        binding.refreshLayout.apply {
            setOnRefreshListener {
                viewModel.sendIntent(SearchRecommendViewModel.SearchUiIntent.SearchHot(key, true))
            }
        }

    }

    override fun initData() {
        viewModel.sendIntent(SearchRecommendViewModel.SearchUiIntent.GetHotSearch())
        viewModel.sendIntent(SearchRecommendViewModel.SearchUiIntent.GetWebSites())
    }

    override fun observeStateAndEvent() {
        viewModel.uiStateFlow.collectFLow(this) {
            when (this) {
                is SearchRecommendViewModel.SearchUiState.IsRefresh -> {
                    binding.refreshLayout.isRefreshing = this.result
                }

                is SearchRecommendViewModel.SearchUiState.Articles -> {
                    this.result?.let {
                        if (it.curPage == 1) {
                            mAdapter.submitList(it.datas)
                        } else {
                            mAdapter.addAll(it.datas)
                        }

                        // 如果在数据不满足一屏时，暂停加载更多，请调用下面方法
                        helper.trailingLoadStateAdapter?.checkDisableLoadMoreIfNotFullPage()
                        if (it.curPage >= it.pageCount) {/*
                            Set the status to not loaded, and there is no paging data.
                            设置状态为未加载，并且没有分页数据了
                             */
                            helper.trailingLoadState = LoadState.NotLoading(true)
                            Toast.makeText(requireActivity(), "没有更多数据了", Toast.LENGTH_SHORT).show()
                        } else {/*
                            Set the state to not loaded, and there is also paginated data
                            设置状态为未加载，并且还有分页数据
                             */
                            helper.trailingLoadState = LoadState.NotLoading(false)
                        }
                    }
                }

                is SearchRecommendViewModel.SearchUiState.WebSites -> {
                    mWebSitesList.clear()
                    mWebSitesList.addAll(this.result)
                    binding.webTagLayout.adapter.notifyDataChanged()
                }

                is SearchRecommendViewModel.SearchUiState.HotSearch -> {
                    mHotList.clear()
                    mHotList.addAll(this.result)
                    binding.hotTagLayout.adapter.notifyDataChanged()
                }

                is SearchRecommendViewModel.SearchUiState.ShowHot -> {
                    binding.hotContent.visibility = if (this.result) View.VISIBLE else View.GONE
                    binding.refreshLayout.visibility = if (this.result) View.GONE else View.VISIBLE
                }

                else -> {}
            }
        }

        viewModel.effectFlow.collectFLow(this) {
            when (this) {
                is LoginViewModel.LoginEvent.ToastEvent -> {
                    requireActivity().toast(
                        this.message, if (this.short) Toast.LENGTH_SHORT else Toast.LENGTH_LONG
                    )
                }
            }
        }
    }
}